import 'dart:async';
import 'dart:math';

import 'package:get/get.dart';
import 'package:largefriends/config/lf_route.dart';
import 'package:largefriends/entity/entities/lf_photo_entity.dart';
import 'package:largefriends/entity/entities/lf_user_entity.dart';
import 'package:largefriends/service/manager/lf_event_helper.dart';
import 'package:largefriends/res.dart';
import 'package:largefriends/service/lf_auth_service.dart';
import 'package:largefriends/widgets/preload_page_view.dart';

import '../../../events/user_relation_event.dart';

toProfilePhotoGallery({required LfUserEntity userEntity, required int index}) {
  Get.toNamed(LFRoute.pathProfilePhotoGallery,
      arguments: {'userEntity': userEntity, 'index': index});
}

toProfileGallery({required LfUserEntity userEntity, required int index}) {
  Get.toNamed(LFRoute.pathProfilePhotoGallery, arguments: {
    'userEntity': userEntity,
    'index': index,
  });
}

class LfProfileGalleryLogic extends GetxController {
  late PreloadPageController controller;
  RxInt currentIndex = 0.obs;
  List<LfPhotoEntity> photos = [];
  late LfUserEntity userEntity;
  int total = 0;
  StreamSubscription? relationSubscription;
  @override
  void onInit() {
    userEntity = Get.arguments['userEntity'];
    photos.addAll(userEntity.publicPhotos());
    if (isSelf) {
      photos.addAll(userEntity.privatePhotos());
      total = photos.length;
    } else {
      if (userEntity.privateAlbumCnt > 0 &&
          userEntity.privatePhotos().isEmpty) {
        photos.add(LfPhotoEntity(type: 2, url: Res.default_private_blur));
      } else {
        photos.addAll(userEntity.privatePhotos());
      }
      total = (max(userEntity.photoCnt, userEntity.publicPhotos().length)) +
          (userEntity.privateAlbumCnt);
    }
    currentIndex.value = Get.arguments['index'];
    controller = PreloadPageController(initialPage: currentIndex.value);
    super.onInit();
    relationSubscription =
        LfEventHelper().getEvent().on<UserRelationEvent>().listen((event) {
      if (event.uid != userEntity.userId) {
        return;
      }
      if (event.type == UserRelationType.requestPrivate) {
        userEntity.privateAlbumStatus = 2;
        update();
      } else if (event.type == UserRelationType.requestAccept) {
        userEntity.canAccessMyPrivate = 1;
        update();
      }
    });
  }

  @override
  void onClose() {
    controller.dispose();
    relationSubscription?.cancel();
    super.onClose();
  }

  bool get isSelf {
    LfAuthService authService = Get.find();
    return authService.currentAccount!.userId == userEntity.userId;
  }
}
